//
//  UDPSorket.m
//  UDPSocket
//
//  Created by Andy JMR on 16/3/31.
//  Copyright © 2016年 JMR. All rights reserved.
//

#import "YSUDPSocket.h"
#import "MQTTCoverTool.h"
#import "YHMarcros.h"
@interface YSUDPSocket () <GCDAsyncUdpSocketDelegate>


@property(nonatomic, strong)GCDAsyncUdpSocket *udpSocket;
@end


@implementation YSUDPSocket

- (void)dealloc
{
   debugLogInfo(@"UDPSocket dealloc");
    
}
- (GCDAsyncUdpSocket *)udpSocket {
    if (!_udpSocket) {
        _udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
        [_udpSocket enableBroadcast:YES error:nil];
    }
    return _udpSocket;
}
- (void)setupUDPSocketBindingPort:(uint16_t)port {
    NSError *error = nil;
    if (![self.udpSocket bindToPort:port error:&error])
    {
       debugLogInfo(@"Error binding: %@", error);
        return;
    }
    if (![self.udpSocket beginReceiving:&error])
    {
       debugLogInfo(@"Error receiving: %@", error);
        return;
    }
   debugLogInfo(@"server ready");

}
- (void) disabled
{
    [_udpSocket  close];
}


- (void)sendData {
    NSString *str = @"hello";
    NSString *host = @"255.255.255.255";
    if ([host length] == 0)
    {
       debugLogInfo(@"Address required");
        return;
    }
    int port = 0x3838;
    if (port <= 0 || port > 65535)
    {
       debugLogInfo(@"Valid port required");
        return;
    }
    NSString *msg = str;
    if ([msg length] == 0)
    {
       debugLogInfo(@"Message required");
        return;
    }
    
    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
    [self.udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
   debugLogInfo(@"Message didConnectToAddress %@",[[NSString alloc]initWithData:address encoding:NSUTF8StringEncoding]);
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError *)error
{
   debugLogInfo(@"Message didNotConnect %@",error);
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error
{
   debugLogInfo(@"Message didNotSendDataWithTag %@",error);
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    BroadcastPack *broadcast  =  [BroadcastPack format:(void*)[data bytes] length:(int)data.length];
    NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
    broadcast.strIP = ip;
    NSLog(@"ip = %@",ip);
    if (broadcast == nil) {
        debugLogInfo(@"error :broadcast = nil");
        return;
    }
    if (broadcast != nil &&  self.delegate != nil && [self.delegate respondsToSelector:@selector(udpSocket:didReceiveData:fromAddress:withFilterContext:)])
    {
        [self.delegate udpSocket:self didReceiveData:broadcast fromAddress:address withFilterContext:filterContext];
    }
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
   debugLogInfo(@"Message didSendDataWithTag");
}

-(void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error
{
   debugLogInfo(@"Message withError %@",error);
}

- (void)sendData:(NSData *)data
          toHost:(NSString *)host
            port:(uint16_t)port
     withTimeout:(NSTimeInterval)timeout
             tag:(long)tag
{
    [self.udpSocket sendData:data toHost:host port:port withTimeout:-1 tag:0];
}
@end
